<template>
	<div class="">
		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				:height="height"
				:checkbox-config="{strict: true}"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template v-if="item.keyName === 'itemList'" #header>
						<div class="flex-start-center">
							<span class="margin-right-10">项目明细</span>
							<div class="margin-right-10">
								<!--<el-checkbox v-model="isSignIn" border size="mini" @change="onSignInChange">签到</el-checkbox>-->
							</div>
							<jk-button v-if="isSignIn" size="mini" type="primary" icon="el-icon-date" @click="onBatchConfirmBtn">确定签到 {{ isSignIn ? checkUpkeepData.length : '' }}个</jk-button>

							<div class="flex-start-center margin-left-10">
								<state-legend class="margin-right-10" :state-list="stateList"></state-legend>
							</div>
						</div>
					</template>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else-if="item.keyName === 'empName'">{{ scope.row.itemList && scope.row.itemList.length ? scope.row.itemList[0].empName : '' }}</span>
						<div v-else-if="item.keyName === 'itemCount'">{{ scope.row.itemList ? scope.row.itemList.length : '0' }}</div>
						<div v-else-if="item.keyName === 'itemList'" class="flex-start-center-wrap">
							<task-list
								:is-sign-in="isSignIn"
								:check-upkeep-data="checkUpkeepData"
								:item-list="scope.row.itemList"
								@change="onSelectUpkeepItem"
								@on-detail="onDetailBtn"
							></task-list>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import { auditStateList } from '@/utils/jk/status-option-list';
    import saveDialog from '../../save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { firstCharacterToLowerCase, pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        machineManagerUpkeepMachineJobMachinePage,
        machineManagerUpkeepMachineJobTaking
    } from '../../../../../../api/machine/upkeepTask';
    import stateLegend from '../../../../../production/afterSpinPrdSchedulingCenter/components/state-legend';
    import { machineManagerUpkeepMachineJobBatchTaking } from '../../../../../../api/machine/machineUpkeepItemConfig';
    import taskList from '../../../machineUpkeepItemConfig/components/task-list';
    import { systemUserColumnConfigGet } from '../../../../../../api/system/column-config';
    import getMenuColumn from '../../../../../../mixins/getMenuColumn';
    export default {
        props: {
            queryParams: {
                type: Object,
                default() {
                    return {};
                }
            },
            height: {
                type: Number,
                default: 0
            }
        },
        components: {
            stateLegend,
            taskList,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn],
        data() {
            return {
                apiItem: {
                    'page': machineManagerUpkeepMachineJobMachinePage
                },
                saveDialogState: false,
                editType: null,
                auditStateList: auditStateList,
                stateList: [
                    { id: 0, name: '计划中', color: '#5cadff' },
                    { id: 1, name: '到期', color: '#ff9900' },
                    { id: 2, name: '保养中', color: '#19be6b' }
                ],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                isCustomDate: false,
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    machineNameOrCode: '',
                    upkeepItemName: '',
                    upkeepTypeId: null,
                    belongDate: []
                },
                isSignIn: false,
                checkUpkeepData: []
            };
        },
        methods: {
            onDetailBtn(e) {
                if (!this.isSignIn && e) {
                    // 计划中和已到期，走'签到'流程，否则走'完成保养'流程
                    if ([0, 1].includes(e.upkeepState)) {
                        this.onTakeBtn(e);
                    } else {
                        this.dataId = e.id;
                        this.saveDialogState = true;
                    }
                }
            },
            onTakeBtn(row) {
                this.$msgbox({
                    title: '消息',
                    message: `确定"保养签到"吗？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            machineManagerUpkeepMachineJobTaking({
                                id: row.id
                            }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    done();
                                    this.getListRequest();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            onSelectUpkeepItem(e) {
                this.checkUpkeepData = e;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            onBatchConfirmBtn() {
                const ids = this.checkUpkeepData.map(x => x.id);
                if (ids.length) {
                    machineManagerUpkeepMachineJobBatchTaking({
                        ids: ids
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.isSignIn = false;
                            tipsBar(this, 'save');
                            this.getListRequest();
                            this.updateParentData();
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '请选择项目!');
                }
            },
            onSignInChange(e) {
                if (!e) {
                    this.checkUpkeepData = [];
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            updateParentData() {
                this.$emit('on-refresh');
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: firstCharacterToLowerCase(this.$route.name), filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res.columnConfigList || [];
                        const arr = resData.find(x => x.code === 'machine-view') ? resData.find(x => x.code === 'machine-view').itemList : [];
                        this.tableColumnList = arr;
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.checkUpkeepData = [];
                this.tableLoading = true;
                this.apiItem.page(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                    }
                });
            }
        },
        mounted() {
            this.getMenuColumnListRequest();
        },
        watch: {
            queryParams: {
                handler(newVal) {
                    const params = newVal ? JSON.parse(JSON.stringify(newVal)) : {};
                    params.ifJob = true;
                    this.searchParams = params;
                },
                deep: true
            }
        }
    };
</script>
